class Solution
{
public:
    int longestEqualSubarray(vector<int> &nums, int k)
    {
        unordered_map<int, vector<int>> intervalsEachNum;
        unordered_map<int, int> lastOccur;
        int n = nums.size();
        for (int i = 0; i < n; ++i)
        {
            if (lastOccur.count(nums[i]))
            {
                intervalsEachNum[nums[i]].push_back(i - lastOccur[nums[i]] - 1);
            }
            lastOccur[nums[i]] = i;
        }
        int maxLen = 0;
        for (auto &[num, intervals] : intervalsEachNum)
        {
            int start = 0;
            int end = 0;
            int sum = 0;

            while (end < intervals.size())
            {
                sum += intervals[end];
                while (sum > k)
                {
                    sum -= intervals[start];
                    start++;
                }
                int len = end - start + 1;
                maxLen = max(maxLen, len);
                end++;
            }
        }
        return maxLen + 1;
    }
};